'use strict';

const BaseController = require('../../core/base_controller');

class ForumController extends BaseController {
  // 获取帖子列表
  async index() {
    const { ctx } = this;
    const { title, category, status, page = 1, pageSize = 10 } = ctx.query;

    // 构建查询条件
    const where = {
      del_flag: 0
    };
    if (title) {
      where.title = {
        [ctx.model.Sequelize.Op.like]: `%${title}%`
      };
    }
    if (category) where.category = category;
    if (status !== undefined) where.status = parseInt(status);

    const { count, rows } = await ctx.model.Forum.findAndCountAll({
      where,
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      attributes: { exclude: ['del_flag'] }
    });

    this.success({
      list: rows,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    });
  }

  // 删除帖子（软删除）
  async destroy() {
    const { ctx } = this;
    const forum = await ctx.model.Forum.findByPk(ctx.params.id);

    if (!forum) {
      ctx.throw(404, '帖子不存在');
    }

    await forum.update({ del_flag: 1 });
    this.success(null, '删除成功');
  }

  // 修改帖子状态
  async updateStatus() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { status } = ctx.request.body;

    const forum = await ctx.model.Forum.findByPk(id);
    if (!forum) {
      ctx.throw(404, '帖子不存在');
    }

    await forum.update({ status: parseInt(status) });
    this.success(null, '状态更新成功');
  }
}

module.exports = ForumController; 